<template>
  <div class="carousel-container w-full">
    <!-- 轮播滑动容器 - 内部容器居中保持原大小 -->
    <div class="carousel-wrapper overflow-hidden">
      <div 
        ref="carouselSlides"
        class="carousel-slides flex transition-transform duration-700 ease-in-out"
        :style="{ transform: `translateX(${-displaySlide * 100 + dragOffset}%)` }"
        @mousedown="handleMouseDown"
        @mousemove="handleMouseMove"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseUp"
        @touchstart="handleMouseDown"
        @touchmove="handleTouchMove"
        @touchend="handleMouseUp"
        @touchcancel="handleMouseUp"
      >
        <!-- 复制最后一张图片到最前面，用于无缝循环 -->
        <div class="carousel-slide min-w-full" :class="slides.length - 1 === 1 || slides.length - 1 === 2 || slides.length - 1 === 4 ? 'flex flex-row bg-transparent' : 'flex flex-col bg-transparent'">
          <!-- 文字内容 -->
          <div class="text-container p-8 md:p-12 bg-opacity-90 backdrop-blur-sm rounded-xl bg-transparent text-gray-900" :class="slides.length - 1 === 1 || slides.length - 1 === 2 || slides.length - 1 === 4 ? 'w-3/4 flex flex-col justify-center' : 'w-full'">
           <h3 class="text-3xl md:text-4xl font-bold mb-4 text-gray-800">
                {{ slides[slides.length - 1].title }}
              </h3>
              <p class="text-gray-600 text-lg md:text-xl mb-8 max-w-4xl">
              {{ slides[slides.length - 1].description }}
            </p>
            <a href="#contact" class="bg-blue-900 text-white px-10 py-4 rounded-full hover:bg-blue-800 hover:shadow-lg transition-all duration-300 font-medium inline-block shadow-md w-40 text-center mx-auto">
              {{ slides[slides.length - 1].buttonText }}
            </a>
          </div>
          
          <!-- 图片内容 -->
          <div class="image-container flex items-center justify-center bg-transparent" :class="slides.length - 1 === 1 || slides.length - 1 === 2 || slides.length - 1 === 4 ? 'w-1/4' : 'w-full'">
            <img 
              :src="slides[slides.length - 1].image" 
              :alt="`Slide ${slides.length}`"
              class="w-full h-auto object-contain mx-auto"
              loading="lazy"
              @mousedown.stop="handleMouseDown"
              @touchstart.stop="handleMouseDown"
              style="pointer-events: none; user-select: none;"
            />
          </div>
        </div>
        
        <!-- 轮播项循环渲染 - 根据索引设置布局 -->
        <div 
            v-for="(slide, index) in slides" 
            :key="index"
            class="carousel-slide min-w-full"
            :class="index === 1 || index === 2 || index === 4 ? 'flex flex-row bg-transparent' : 'flex flex-col bg-transparent'"
          >
          <!-- 文字内容 -->
          <div class="text-container p-8 md:p-12 bg-opacity-90 backdrop-blur-sm rounded-xl bg-transparent text-gray-900" :class="index === 1 || index === 2 || index === 4 ? 'w-3/4 flex flex-col justify-center' : 'w-full'">
           <h3 class="text-3xl md:text-4xl font-bold mb-4 text-gray-800">
                {{ slide.title }}
              </h3>
              <p class="text-gray-600 text-lg md:text-xl mb-8 max-w-4xl">
              {{ slide.description }}
            </p>
            <a href="#contact" class="bg-blue-900 text-white px-10 py-4 rounded-full hover:bg-blue-800 hover:shadow-lg transition-all duration-300 font-medium inline-block shadow-md w-40 text-center mx-auto">
              {{ slide.buttonText }}
            </a>
          </div>
          
          <!-- 图片内容 -->
          <div class="image-container flex items-center justify-center bg-transparent" :class="index === 1 || index === 2 || index === 4 ? 'w-1/4' : 'w-full'">
            <img 
              :src="slide.image" 
              :alt="`Slide ${index + 1}`"
              class="w-full h-auto object-contain mx-auto"
              loading="lazy"
              @load="onImageLoad"
              @mousedown.stop="handleMouseDown"
              @touchstart.stop="handleMouseDown"
              style="pointer-events: none; user-select: none;"
            />
          </div>
        </div>
        
        <!-- 复制第一张图片到最后面，用于无缝循环 -->
        <div class="carousel-slide min-w-full" :class="0 === 1 || 0 === 2 || 0 === 4 ? 'flex flex-row bg-transparent' : 'flex flex-col bg-transparent'">
          <!-- 文字在图片头部 -->
          <div class="text-container p-8 md:p-12 bg-opacity-90 backdrop-blur-sm rounded-xl bg-transparent text-gray-900" :class="0 === 1 || 0 === 2 || 0 === 4 ? 'w-3/4 flex flex-col justify-center' : 'w-full'">
           <h3 class="text-3xl md:text-4xl font-bold mb-4 text-gray-800">
                {{ slides[0].title }}
              </h3>
              <p class="text-gray-600 text-lg md:text-xl mb-8 max-w-4xl">
              {{ slides[0].description }}
            </p>
            <a href="#contact" class="bg-blue-900 text-white px-10 py-4 rounded-full hover:bg-blue-800 hover:shadow-lg transition-all duration-300 font-medium inline-block shadow-md w-40 text-center mx-auto">
              {{ slides[0].buttonText }}
            </a>
          </div>
          
          <!-- 图片在文字下方，根据原始比例显示 -->
          <div class="image-container flex items-center justify-center bg-transparent" :class="0 === 1 || 0 === 2 || 0 === 4 ? 'w-1/4' : 'w-full'">
            <img 
              :src="slides[0].image" 
              :alt="`Slide 1`"
              class="w-full h-auto object-contain mx-auto"
              loading="lazy"
              @mousedown.stop="handleMouseDown"
              @touchstart.stop="handleMouseDown"
              style="pointer-events: none; user-select: none;"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 轮播控制按钮 - 位于轮播图左右外侧的中间部分，与轮播图保持更大距离 -->
    <button 
      class="absolute left-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-full flex items-center justify-center transition-all hover:scale-105 z-10 shadow-lg bg-white text-black"
      @click="prevSlide"
      aria-label="上一张"
    >
      <i class="fa fa-chevron-left"></i>
    </button>
    <button 
      class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-full flex items-center justify-center transition-all hover:scale-105 z-10 shadow-lg bg-white text-black"
      @click="nextSlide"
      aria-label="下一张"
    >
      <i class="fa fa-chevron-right"></i>
    </button>
    
    <!-- 轮播指示器 - 移到图片下方 -->
    <div class="carousel-indicators flex justify-center mt-6 space-x-3">
        <button 
          v-for="(slide, index) in slides" 
          :key="index"
          class="w-2 h-2 rounded-full transition-all duration-200"
          :class="{ 'bg-black w-6': index === currentSlide - 1, 'bg-black/40': index !== currentSlide - 1 }"
          @click="goToSlide(index)"
          :aria-label="`转到幻灯片 ${index + 1}`"
        ></button>
      </div>
  </div>
</template>

<script>
export default {
  name: 'Carousel',
  data() {
    return {
      currentSlide: 1, // 初始显示第一张真实幻灯片（索引为1，因为前面添加了一个复制的最后一张）
      displaySlide: 1, // 用于显示的幻灯片索引
      isDragging: false,
      startX: 0,
      dragOffset: 0,
      originalDisplaySlide: 1,
      slides: [
        {
          image: '/slider1.png',
          title: '地理 SEO：精准定位您的本地客户群',
          description: '我们的地理SEO服务帮助您的业务在特定地理区域内获得显著优势，通过优化地理位置标签、本地关键词和地图列表，确保您的企业在目标区域的搜索结果中排名靠前，吸引真正有需求的本地客户。',
          buttonText: '了解更多'
        },
        {
          image: '/slider2.png',
          title: '全面 SEO 优化解决方案',
          description: '我们提供全方位的SEO优化服务，从技术架构优化到内容策略制定，从关键词研究到用户体验提升。我们的SEO专家团队将为您的网站量身定制优化方案，提升有机搜索排名，增加高质量流量，并最大化转化率。',
          buttonText: '了解更多'
        },
        {
          image: '/slider3.png',
          title: 'Geo围栏营销：精准触达目标受众',
          description: '通过先进的Geo围栏技术，我们能够在特定地理区域内精准投放您的广告，触达最有可能转化的潜在客户。结合SEO策略，我们的Geo营销方案帮助您在竞争激烈的市场中脱颖而出，实现投资回报率最大化。',
          buttonText: '了解更多'
        },
        {
          image: '/slider4.png',
          title: '跨国 SEO 优化：突破地域限制',
          description: '我们的跨国SEO服务帮助您的业务突破地域限制，在全球范围内获得更多曝光。通过多语言SEO策略、地域化内容优化和国际化网站架构设计，我们确保您的业务在不同国家和地区的搜索引擎中都能获得良好排名。',
          buttonText: '了解更多'
        },
        {
          image: '/slider5.png',
          title: 'SEO 数据分析与持续优化',
          description: '我们不仅提供初始SEO优化，还通过专业的数据分析和持续监控，不断调整优化策略。利用先进的SEO分析工具，我们跟踪关键指标，识别改进机会，并实施数据驱动的优化措施，确保您的网站持续保持竞争优势。',
          buttonText: '了解更多'
        }
      ],
      autoplayInterval: null,
      imageDimensions: {}
    }
  },
  mounted() {
    this.startAutoplay();
  },
  beforeUnmount() {
    this.stopAutoplay();
  },
  methods: {
    startAutoplay() {
      this.autoplayInterval = setInterval(() => {
        this.nextSlide();
      }, 5000);
    },
    stopAutoplay() {
      if (this.autoplayInterval) {
        clearInterval(this.autoplayInterval);
      }
    },
    nextSlide() {
      this.displaySlide = this.currentSlide + 1;
      this.currentSlide++;
      
      // 当滚动到最后一个复制的幻灯片时，无动画切回第一个真实幻灯片
      if (this.currentSlide > this.slides.length) {
        setTimeout(() => {
          this.currentSlide = 1;
          // 关闭过渡动画
          if (this.$refs.carouselSlides) {
            this.$refs.carouselSlides.style.transition = 'none';
          }
          this.displaySlide = 1;
          // 下一帧重新开启过渡动画
          setTimeout(() => {
            if (this.$refs.carouselSlides) {
              this.$refs.carouselSlides.style.transition = 'transform 600ms ease-out';
            }
          }, 50);
        }, 600);
      }
    },
    prevSlide() {
      this.displaySlide = this.currentSlide - 1;
      this.currentSlide--;
      
      // 当滚动到最前面复制的幻灯片时，无动画切回最后一个真实幻灯片
      if (this.currentSlide < 1) {
        setTimeout(() => {
          this.currentSlide = this.slides.length;
          // 关闭过渡动画
          if (this.$refs.carouselSlides) {
            this.$refs.carouselSlides.style.transition = 'none';
          }
          this.displaySlide = this.slides.length;
          // 下一帧重新开启过渡动画
          setTimeout(() => {
            if (this.$refs.carouselSlides) {
              this.$refs.carouselSlides.style.transition = 'transform 600ms ease-out';
            }
          }, 50);
        }, 600);
      }
    },
    goToSlide(index) {
      // 转换为真实的幻灯片索引（+1 因为前面添加了一个复制的最后一张）
      this.currentSlide = index + 1;
      this.displaySlide = index + 1;
    },
    onImageLoad(event) {
      // 图片加载完成后可以获取其原始尺寸
      const img = event.target;
      const index = parseInt(img.alt.split(' ')[1]) - 1;
      // 在Vue 3中直接修改reactive属性
      this.imageDimensions[index] = {
        width: img.naturalWidth,
        height: img.naturalHeight
      };
      
      // 根据图片尺寸动态调整容器样式
      this.adjustImageContainer(index, img.naturalWidth, img.naturalHeight);
    },
    adjustImageContainer(index, width, height) {
      // 可以根据图片的宽高比进行更精细的调整
      const aspectRatio = width / height;
      
      // 这里可以添加更多的逻辑来根据不同的宽高比调整样式
      console.log(`Slide ${index + 1} aspect ratio: ${aspectRatio.toFixed(2)}`);
    },
    
    // 鼠标按下事件
    handleMouseDown(event) {
      // 停止自动播放
      this.stopAutoplay();
      
      // 记录鼠标按下位置和当前显示的幻灯片索引
      this.isDragging = true;
      this.startX = event.clientX;
      this.originalDisplaySlide = this.displaySlide;
      
      // 禁用过渡动画以便拖动时更流畅
      if (this.$refs.carouselSlides) {
        this.$refs.carouselSlides.style.transition = 'none';
      }
    },
    
    // 鼠标移动事件
    handleMouseMove(event) {
      if (!this.isDragging) return;
      
      // 计算拖动距离并转换为百分比
      const currentX = event.clientX;
      const deltaX = currentX - this.startX;
      const slideWidth = this.$refs.carouselSlides.offsetWidth;
      this.dragOffset = (deltaX / slideWidth) * 100;
    },
    
    // 触摸移动事件（移动端支持）
    handleTouchMove(event) {
      if (!this.isDragging) return;
      
      // 使用触摸事件的第一个触点
      const touch = event.touches[0];
      const currentX = touch.clientX;
      const deltaX = currentX - this.startX;
      const slideWidth = this.$refs.carouselSlides.offsetWidth;
      this.dragOffset = (deltaX / slideWidth) * 100;
      
      // 防止页面滚动
      event.preventDefault();
    },
    
    // 鼠标松开事件
    handleMouseUp() {
      if (!this.isDragging) return;
      
      // 重新启用过渡动画
      if (this.$refs.carouselSlides) {
        this.$refs.carouselSlides.style.transition = 'transform 600ms ease-out';
      }
      
      // 判断是否需要切换幻灯片（拖动距离超过10%则切换）
      const threshold = 10;
      if (this.dragOffset > threshold) {
        // 向右拖动超过阈值，显示上一张
        this.prevSlide();
      } else if (this.dragOffset < -threshold) {
        // 向左拖动超过阈值，显示下一张
        this.nextSlide();
      } else {
        // 拖动距离不足阈值，回到原始幻灯片
        this.displaySlide = this.originalDisplaySlide;
      }
      
      // 重置拖动状态和偏移量
      this.isDragging = false;
      this.dragOffset = 0;
      
      // 重新开始自动播放
      this.startAutoplay();
    }
  }
}
</script>

<style scoped>
.carousel-container {
  position: relative;
  width: 100%;
  min-height: 400px;
  height: auto;
  background-color: transparent; /* 移除背景颜色 */
  margin: 0; /* 让容器贴在屏幕两侧 */
  z-index: 10; /* 确保轮播图在导航栏下方 */
  display: block;
}

.carousel-wrapper {
  overflow: hidden;
  position: relative;
  width: 100%;
  max-width: 1000px; /* 保持内部容器大小 */
  margin: 0 auto; /* 内部容器居中 */
  min-height: 400px; /* 确保高度一致 */
  height: 100%;
  display: block;
  background-color: transparent; /* 确保没有背景颜色 */
}

.carousel-slides {
  display: flex;
  width: 100%;
}

.carousel-slide {
  min-width: 100%;
  position: relative;
}

.text-container {
  text-align: center;
  padding: 30px 20px 30px; /* 减少内边距，控制整体高度 */
  background-color: #F9FAFB; /* 对应bg-gray-50 */
  margin-top: 0; /* 恢复为0，因为父容器已经有padding-top */
  position: relative;
  z-index: 10;
}

/* 为水平布局的幻灯片文本容器添加样式 */
.carousel-slide.flex.flex-row .text-container {
  background-color: transparent;
  min-height: 400px;
}

.image-container {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
}

.carousel-slide img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
  display: block;
  margin: 0 auto;
}

/* 移除之前的限制 */

.carousel-indicators {
  margin-top: 20px;
  margin-bottom: 20px;
}

.carousel-indicators button {
  cursor: pointer;
  border: none;
  outline: none;
  background: transparent;
  color: #4B5563; /* text-gray-700 */
  font-size: 20px;
}

.carousel-indicators button:hover {
  color: #1E3A8A; /* text-blue-900 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .text-container {
    padding: 25px 15px 25px;
  }
  
  .carousel-slide img {
    max-height: 300px;
  }
  
  .carousel-slide.flex.flex-row .text-container {
    min-height: auto;
    padding: 20px 15px;
  }
  
  .carousel-indicators {
    margin-top: 15px;
    margin-bottom: 15px;
  }
  
  /* 优化移动端触摸滑动 */
  .carousel-wrapper {
    touch-action: pan-y;
    -webkit-overflow-scrolling: touch;
  }
  
  .text-container h3 {
  font-size: 2.5rem;
}
  
  .text-container p {
    font-size: 1rem;
  }
  
  .carousel-slide img {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    max-height: 300px;
  }
  
  /* 在小屏幕上重置为默认垂直布局 */
  .carousel-slide.flex {
    flex-direction: column;
  }
  
  .carousel-slide.flex .text-container,
  .carousel-slide.flex .image-container {
    width: 100%;
    text-align: center;
  }
}

@media (max-width: 480px) {
  .text-container {
    padding: 25px 10px;
  }
  
  .text-container h3 {
    font-size: 2rem;
  }
  
  .text-container p {
    font-size: 0.9rem;
  }
  
  .carousel-slide img {
    max-height: 250px;
  }
}
</style>